package org.keyroy.map.render;

import java.awt.Point;

import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.RGB;
import org.keyroy.map.core.manages.Resource;
import org.keyroy.map.core.manages.ResourceManage;
import org.keyroy.map.core.sprite.Sprite;
import org.keyroy.util.KMap;

public class SWTResourceLoader {
	private static final RGB transparentColor = new RGB(0x12, 0x34, 0x56);
	
	public static KMap<Image> swtImageBuf = new KMap<Image>();
	
	public static final Image getSWTImage(Sprite sprite) {
		if (sprite.obj != null) {
			return (Image) sprite.obj;
		} else {
			Resource resource = ResourceManage.getResource(sprite);
			if (resource == null) {
				sprite.ID = Sprite.SPRITE_DELETE_ID;
				return null;
			}

			Image image = getSWTImage(resource, sprite.getQueueID());
			sprite.obj = image;
			return image;
		}

	}

	private static final Image getSWTImage(Resource resource, int queueID) {
		if (resource == null) {
			return null;
		}
		Image image = swtImageBuf.get(resource.ID, queueID);
		if (image == null) {
			prepareSWTImage(resource, queueID);
		} else {
			return image;
		}
		return swtImageBuf.get(resource.ID, queueID);
	}

	public static void prepareSWTImage(Resource resource, int queueID) {
		try {
			if (resource.obj == null) {
				resource.obj = new Image(null, resource.filePath);
			}

			if (resource.splited) {
				Point out = new Point();
				resource.getLocation(queueID, out);

				ImageData imageData = new ImageData(resource.pw, resource.ph, 32,
						((Image) resource.obj).getImageData().palette);
				imageData.transparentPixel = imageData.palette.getPixel(transparentColor);
				Image image = new Image(null, imageData);

				GC gc = new GC(image);
				gc.setBackground(new Color(null, transparentColor));
				gc.fillRectangle(0, 0, resource.pw, resource.ph);
				gc.drawImage((Image) (resource.obj), -out.x, -out.y);
				gc.dispose();

				swtImageBuf.set(resource.ID, queueID, image);
			} else {
				swtImageBuf.set(resource.ID, 0, (Image) resource.obj);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
